from django.shortcuts import render, get_object_or_404
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
import update_user

from forms import SignatureForm

def profile(request, user_id=None, editted='False', template_name="lbforum/account/profile.html"):
    view_user = request.user
    if user_id:
        view_user = get_object_or_404(User, pk = user_id)
    view_only = view_user != request.user
    ext_ctx = {'view_user':view_user, 'view_only':view_only }

    if editted == 'update': 
        ext_ctx['update_msg'] = 'Your linked accounts have been updated and synced!'    

    return render(request, template_name, ext_ctx)

# Modify your trust account names or refresh your accounts data
def modify_trust_profile(request, user_id=None, template_name="lbforum/account/profile.html"):
    view_user = request.user
    if user_id:
        view_user = get_object_or_404(User, pk = user_id)
    view_only = view_user != request.user
    ext_ctx = {'view_user':view_user, 'view_only':view_only }

    post =  request.POST
    trust_profile = view_user.trust_profile
    trust_profile.trust_ebay_acct_name = post['trust_ebay_acct_name'] 
    trust_profile.trust_airbnb_acct_name = post['trust_airbnb_acct_name'] 
    trust_profile.trust_gar_acct_name = post['trust_gar_acct_name'] 
    trust_profile.save()

    if post.get('update', ''):
        update_user.update_user(view_user.username)
        return HttpResponseRedirect(reverse("trust_edit_profile", args=[view_user.id, 'update']))

    return render(request, template_name, ext_ctx)

@login_required
def signature(request, form_class=SignatureForm, template_name="lbforum/account/signature.html"):
    profile = request.user.lbforum_profile
    if request.method == "POST":
        form = form_class(instance=profile, data=request.POST)
        form.save()
    else:
        form = form_class(instance=profile)
    ext_ctx = {'form': form}
    return render(request, template_name, ext_ctx)
